import { BadRequestException, Global, MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AdminModule } from './admin/admin.module';
// cache
import { CacheModule } from '@nestjs/cache-manager';
// typeORM
import { TypeOrmModule } from '@nestjs/typeorm';
// import { AuthMiddleware } from './common/auth/auth.middleware';
import { CommonMiddleware } from './common/common.middleware';
import { RedisModule } from './redis/redis.module';
import { mysqlConfig } from './utils/config';
import { ChatModule } from './chat/chat.module';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { MenuModule } from './menu/menu.module';
import { RoleModule } from './role/role.module';
import { OrganizationModule } from './organization/organization.module';
import { DepartmentModule } from './department/department.module';
import { GoodsModule } from './erp/goods/goods.module';
import { GoodsCategoryModule } from './erp/goods-category/goods-category.module';
import { SupplierModule } from './erp/supplier/supplier.module';
import { WarehouseModule } from './erp/warehouse/warehouse.module';
import { PurchaseModule } from './erp/purchase/purchase.module';
@Global()
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: mysqlConfig.host || '192.168.1.100',
      port: 3306,
      username: mysqlConfig.username || 'naiveui',
      password: mysqlConfig.password || 'naiveui9008',
      database: mysqlConfig.database || 'naiveui',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: !!process.env.IS_SYNCHRONIZE,
      entityPrefix: mysqlConfig.entityPrefix || 'n_',
      extra:{
        dateStrings: true
      },
      logging: true,
      logger: 'advanced-console',
    }),
    MulterModule.register({
      storage: diskStorage({
        destination: './uploads', // 指定上传目录
        filename: (req, file, cb) => {
          const fileExtName = extname(file.originalname); // 获取文件的原始扩展名
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
          cb(null, `${file.fieldname}-${uniqueSuffix}${fileExtName}`); // 使用原始扩展名
        },
      }),
      limits: {
        fileSize: 50 * 1024 * 1024
      },
      fileFilter(request, file, cal) {
          const ext = extname(file.originalname);
          if (['.jpg', '.png', '.jpeg'].includes(ext)) {
            return cal(null, true);
          } else {
            return cal(new BadRequestException('文件格式错误'), false);
          }
        }
    }),
    CacheModule.register(),
    AdminModule, 
    RedisModule,
    ChatModule,
    MenuModule,
    RoleModule,
    OrganizationModule,
    DepartmentModule,
    GoodsModule,
    GoodsCategoryModule,
    SupplierModule,
    WarehouseModule,
    PurchaseModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(CommonMiddleware)
      .forRoutes({
        path: "*",
        method: RequestMethod.ALL
      });
  }
}
